package weixin.util;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import weixin.pojo.User;

public class InterfaceUtil {
	private static Logger logger = LoggerFactory.getLogger(InterfaceUtil.class);
	public static final String AppID = "wxb9ae015f37b92a0f";
	public static final String Appsecret = "12435a57dc4909adfae89dd7055487fc";

	public static final String Language_CN = "zh_CN";
	public static final String Language_TW = "zh_TW";
	public static final String Language_EN = "en";

	public static final String Interface_AccessToken_Url = "https://api.weixin.qq.com/cgi-bin/token";
	public static final String Interface_UserInfo_Url = "https://api.weixin.qq.com/cgi-bin/user/info";

	public static String AccessToken = "";
	public static long LastTime;

	public static String getAccessToken() {
		synchronized (AccessToken) {
			if (AccessToken.length() == 0
					|| new Date().getTime() - LastTime > 7200000) {
				Map<String, String> datas = new HashMap<String, String>();
				datas.put("grant_type", "client_credential");
				datas.put("appid", AppID);
				datas.put("secret", Appsecret);
				String json = HttpUtil.get1(Interface_AccessToken_Url, datas);
				logger.info("AccessToken json is: " + json);
				if (json != null && json.length() > 0) {
					JSONObject jsonObj = JSONObject.fromObject(json);
					if (jsonObj.containsKey("access_token")) {
						AccessToken = jsonObj.getString("access_token");
						LastTime = new Date().getTime();
					}
				}
				logger.info("AccessToken is: " + AccessToken);
			}
		}
		return AccessToken;
	}

	public static User getUser(String openID) {
		User user = new User();
		Map<String, String> datas = new HashMap<String, String>();
		datas.put("access_token", getAccessToken());
		datas.put("openid", openID);
		datas.put("lang", Language_CN);
		String json = HttpUtil.get1(Interface_UserInfo_Url, datas);
		if (json != null && json.length() > 0) {
			JSONObject jsonObj = JSONObject.fromObject(json);
			if (jsonObj.containsKey("nickname")) {
				user.setNickname(jsonObj.getString("nickname"));
			}
		}
		return user;
	}

	public static void main(String[] args) {
		getUser("owDSbt3mcyHKdTzNAfAkuYaCwZEU");
	}
}
